package com.zhoug.ocr.textin.parser;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import com.zhoug.common.utils.GsonUtils;
import com.zhoug.common.utils.JsonUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StringUtils;
import com.zhoug.ocr.textin.data.FormResult;
import com.zhoug.ocr.textin.data.FormTable;
import com.zhoug.ocr.textin.data.HeaderField;
import com.zhoug.ocr.textin.data.TableCell;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: zhoug
 * @Date: 2023/3/2
 * @Description:
 */
public abstract class BaseFormResultParser implements FormResultParser {
    protected static final String TAG = ">>>BaseFormResultParser";
    protected static boolean DEBUG = true;

    /**
     * 去掉空数据的单元格
     *
     * @param formResult
     * @return
     */
    public FormResult filterEmptyRowCol(FormResult formResult) {
        if (formResult != null) {
            List<FormTable> tables = formResult.getTables();
            if (tables != null && tables.size() > 0) {
                for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) {
                    FormTable formTable = tables.get(tableIndex);
                    if (formTable != null) {
                        List<TableCell> table_cells = formTable.getTable_cells();
                        if (DEBUG) {
                            LogUtils.d(TAG, "passEmptyRowCol:table_cells=" + JsonUtils.toJson(table_cells));
                        }
                        if (table_cells != null && table_cells.size() > 0) {
                            Iterator<TableCell> iterator = table_cells.iterator();
                            while (iterator.hasNext()) {
                                TableCell tableCell = iterator.next();
                                String cellText = formatText(tableCell.getText());
                                if (StringUtils.isNullOrEmpty(cellText)) {
                                    iterator.remove();
                                } else {
                                    tableCell.setText(cellText);
                                }
                            }
                        }
                    }
                }
            }
        }
        if (DEBUG) {
            LogUtils.d(TAG, "passEmptyRowCol:" + JsonUtils.toJson(formResult));
        }

        return formResult;
    }

    /**
     * 找出表头
     *
     * @param formResult
     * @param headerFields
     * @return
     */
    public List<HeaderField> parseHeader(FormResult formResult, List<HeaderField> headerFields) {
        if (headerFields == null || headerFields.size() == 0) return null;
        List<HeaderField> headers = null;
        if (formResult != null) {
            List<FormTable> tables = formResult.getTables();
            if (tables != null && tables.size() > 0) {
                headers = new ArrayList<>();
                for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) {
                    FormTable formTable = tables.get(tableIndex);
                    if (formTable != null) {
                        List<TableCell> table_cells = formTable.getTable_cells();
                        if (table_cells != null && table_cells.size() > 0) {
                            for (TableCell tableCell : table_cells) {
                                String text = tableCell.getText();
                                for (HeaderField item : headerFields) {
                                    if (item.getName().equalsIgnoreCase(text)) {
                                        HeaderField headerField = new HeaderField();
                                        headerField.setName(item.getName());
                                        headerField.setField(item.getField());
                                        headerField.setStartRow(tableCell.getStart_row());
                                        headerField.setEndRow(tableCell.getEnd_row());
                                        headerField.setStartCol(tableCell.getStart_col());
                                        headerField.setEndCol(tableCell.getEnd_col());
                                        headers.add(headerField);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (DEBUG) {
            LogUtils.d(TAG, "parseHeader 找出表头 :" + (headers != null ? JsonUtils.toJson(headers) : null));

        }
        //表头去重
        if (headers != null && headers.size() > 0) {
            Map<Integer, List<HeaderField>> map = new HashMap<>();
            for (HeaderField item : headers) {
                String name = item.getName();
                int startRow = item.getStartRow();
                int endRow = item.getEndRow();
                if (map.size() == 0) {
                    List<HeaderField> list = new ArrayList<>();
                    list.add(item);
                    map.put(startRow, list);
                } else {
                    List<HeaderField> list = map.get(startRow);
                    if (list != null) {
                        list.add(item);
                    } else {
                        list = new ArrayList<>();
                        list.add(item);
                        map.put(startRow, list);
                    }
                }
            }

            if (DEBUG) {
                LogUtils.d(TAG, "parseHeader :" + JsonUtils.toJson(map));

            }
            Iterator<Integer> iterator = map.keySet().iterator();
            int count = 0;
            List<HeaderField> resultHeaders = null;
            while (iterator.hasNext()) {
                Integer key = iterator.next();
                List<HeaderField> value = map.get(key);
                if (value != null && value.size() > count) {
                    resultHeaders = value;
                    count = value.size();
                }
            }
            headers = resultHeaders;
        }
        if (DEBUG) {
            LogUtils.d(TAG, "headers 表头去重 :" + JsonUtils.toJson(headers));
        }
        return headers;
    }

    /**
     * 按照表头顺序格式化
     *
     * @param headers
     * @param headerFields
     * @return
     */
    public List<HeaderField> parseHeaderByOrder(List<HeaderField> headers, List<HeaderField> headerFields) {
        if (headerFields == null || headerFields.size() == 0) return null;
        if (headers != null && headers.size() > 0) {
            int headerIndex = 0;
            HeaderField headerField = null;
            out:
            for (int i = 0; i < headerFields.size(); i++) {
                HeaderField field1 = headerFields.get(i);
                for (HeaderField field2 : headers) {
                    if (field1.getField().equals(field2.getField())) {
                        headerField = field2;
                        headerIndex = i;
                        break out;
                    }
                }
            }

            int startRow = headerField.getStartRow();
            int endRow = headerField.getEndRow();
            int startCol = headerField.getStartCol();
            int endCol = headerField.getEndCol();
            for (int i = 0; i < headerFields.size(); i++) {
                HeaderField headerField1 = headerFields.get(i);
                headerField1.setStartRow(startRow);
                headerField1.setEndRow(endRow);
                if (i == headerIndex) {
                    headerField1.setStartCol(startCol);
                    headerField1.setEndCol(endCol);
                } else if (i < headerIndex) {
                    headerField1.setStartCol(startCol - (headerIndex - i));
                    headerField1.setEndCol(endCol - (headerIndex - i));
                } else {
                    headerField1.setStartCol(startCol + (i - headerIndex));
                    headerField1.setEndCol(endCol + (i - headerIndex));
                }
            }
        }
        if (DEBUG) {
            LogUtils.d(TAG, "parseHeaderByOrder 按照表头顺序格式化 :" + JsonUtils.toJson(headerFields));
        }
        return headerFields;
    }


    public JsonObject getJsonObject(JsonArray jsonArray, int startRow, int endRow) {
        int size = jsonArray.size();
        JsonObject jsonObject = null;
        for (int i = 0; i < size; i++) {
            JsonObject item = jsonArray.get(i).getAsJsonObject();
            if (GsonUtils.getAsInt(item, "startRow", Integer.MAX_VALUE) == startRow
                    && GsonUtils.getAsInt(item, "endRow", Integer.MAX_VALUE) == endRow
            ) {
                jsonObject = item;
                break;
            }
        }
        if (jsonObject == null) {
            jsonObject = new JsonObject();
            jsonObject.addProperty("startRow", startRow);
            jsonObject.addProperty("endRow", endRow);
            jsonArray.add(jsonObject);
        }
        return jsonObject;
    }


    public String formatText(String text) {
        if (!StringUtils.isNullOrEmpty(text)) {
            text = text.trim();
            Pattern pattern = Pattern.compile("\t|\r|\n|\\s*");
            Matcher matcher = pattern.matcher(text);
            text = matcher.replaceAll("");

            return text;
        }
        return null;
    }

    /**
     * 如果HeaderField的Field为空则赋值默认值
     *
     * @param headerFields
     */
    public List<HeaderField> setHeaderDefaultField(List<HeaderField> headerFields) {
        int i = 1;
        for (HeaderField item : headerFields) {
            if (StringUtils.isNullOrEmpty(item.getField())) {
                item.setField("key" + i);
                i++;
            }
        }
        return headerFields;
    }
}
